import json
from typing import Dict, Optional, Set, Any
from fastapi import WebSocket
from game_logic import GameState


class RoomManager:
    """房间管理器"""
    
    def __init__(self):
        self.rooms: Dict[str, GameState] = {}
        self.player_connections: Dict[str, WebSocket] = {}
        self.room_players: Dict[str, Set[str]] = {}  # 房间ID -> 玩家ID集合
    
    def create_or_join_room(self, room_id: str, player_id: str, websocket: WebSocket) -> Dict[str, Any]:
        """创建或加入房间"""
        # 如果房间不存在，创建新房间
        if room_id not in self.rooms:
            self.rooms[room_id] = None  # 游戏状态将在两个玩家都加入后初始化
            self.room_players[room_id] = set()
        
        # 检查房间是否已满
        if len(self.room_players[room_id]) >= 2:
            return {"success": False, "error": "Room is full"}
        
        # 检查玩家是否已在房间中
        if player_id in self.room_players[room_id]:
            return {"success": False, "error": "Player already in room"}
        
        # 加入房间
        self.room_players[room_id].add(player_id)
        self.player_connections[player_id] = websocket
        
        # 如果房间现在有2个玩家，初始化游戏
        if len(self.room_players[room_id]) == 2:
            players = list(self.room_players[room_id])
            self.rooms[room_id] = GameState(players[0], players[1])
            
            # 不再自动初始化游戏，等待双方选择卡组
            # 游戏状态将在双方都选择卡组后初始化
            
            return {
                "success": True,
                "message": "Room full, game starting",
                "game_initialized": True,
                "players": players
            }
        else:
            return {
                "success": True,
                "message": "Waiting for other player",
                "game_initialized": False,
                "players": list(self.room_players[room_id])
            }
    
    def is_room_full(self, room_id: str) -> bool:
        """检查房间是否已满"""
        return room_id in self.room_players and len(self.room_players[room_id]) >= 2
    
    def get_game_state(self, room_id: str) -> Optional[GameState]:
        """获取游戏状态"""
        return self.rooms.get(room_id)
    
    def get_room_players(self, room_id: str) -> Set[str]:
        """获取房间中的玩家"""
        return self.room_players.get(room_id, set())
    
    async def broadcast_to_room(self, room_id: str, message: Dict[str, Any]):
        """向房间中的所有玩家广播消息"""
        if room_id not in self.room_players:
            return
        
        for player_id in self.room_players[room_id]:
            if player_id in self.player_connections:
                try:
                    await self.player_connections[player_id].send_text(json.dumps(message))
                except Exception as e:
                    print(f"Failed to send message to player {player_id}: {e}")
    
    async def send_to_player(self, player_id: str, message: Dict[str, Any]):
        """向特定玩家发送消息"""
        if player_id in self.player_connections:
            try:
                await self.player_connections[player_id].send_text(json.dumps(message))
            except Exception as e:
                print(f"Failed to send message to player {player_id}: {e}")
    
    def remove_player(self, room_id: str, player_id: str):
        """移除玩家"""
        if room_id in self.room_players:
            self.room_players[room_id].discard(player_id)
            
            # 如果房间为空，删除房间
            if not self.room_players[room_id]:
                del self.room_players[room_id]
                if room_id in self.rooms:
                    del self.rooms[room_id]
        
        # 移除连接
        if player_id in self.player_connections:
            del self.player_connections[player_id]
    
    def get_player_room(self, player_id: str) -> Optional[str]:
        """获取玩家所在的房间"""
        for room_id, players in self.room_players.items():
            if player_id in players:
                return room_id
        return None
    
    def get_all_rooms_info(self) -> Dict[str, Any]:
        """获取所有房间的信息"""
        rooms_info = []
        for room_id, players in self.room_players.items():
            rooms_info.append({
                "room_id": room_id,
                "player_count": len(players),
                "max_players": 2
            })
        return {"rooms": rooms_info}
    
    def destroy_room(self, room_id: str):
        """销毁房间"""
        if room_id in self.room_players:
            # 移除所有玩家连接
            for player_id in self.room_players[room_id]:
                if player_id in self.player_connections:
                    del self.player_connections[player_id]
            
            # 删除房间
            del self.room_players[room_id]
            if room_id in self.rooms:
                del self.rooms[room_id]
            
            print(f"Room {room_id} destroyed")


# 全局房间管理器实例
room_manager = RoomManager()
